package com.liusuai.yixian.update;

import com.liusuai.yixian.config.StrConfig;
import com.liusuai.yixian.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URL;


@RestController
public class DownloadControler {

    @Autowired
    protected StrConfig strConfig;

    private static Logger logger = LoggerFactory.getLogger(DownloadControler.class);

    @RequestMapping(value = "/download/{name}", method = RequestMethod.GET)
    public void downLoad(@PathVariable("name") String name,
                         HttpServletRequest request,
                         HttpServletResponse response) {

        if (name == null || "".equals(name)) {
            logger.error("file is not exist!");
            return;
        }
        String filename = "/static/voices/" + name;
        logger.info("file filename is:" + filename);

        try {
            URL url = DownloadControler.class.getResource(filename);

            String path = url.getPath();
            File zipFile = new File(path);

            if (zipFile.exists()) { //判断文件父目录是否存在
                FileUtils.downloadFile(zipFile, response);

            } else {
                logger.error("file is not exist!");
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }

        return;
    }

    //下载服务器本地文件
    @RequestMapping(value = "/download/local/{name}", method = RequestMethod.GET)
    @ResponseBody
    public String downLoadLocal(@PathVariable("name") String name,
                                HttpServletRequest request,
                                HttpServletResponse response) {

        String filepath = strConfig.getLocalResDir() + name;
        logger.info("file filepath is:" + filepath);


        File zipFile = new File(filepath);

        if (zipFile.exists()) { //判断文件父目录是否存在
            FileUtils.downloadFile(zipFile, response);

        } else {
            logger.error("file is not exist!");
        }
        return null;
    }

}

